<template>
    <div class="table_container">
        <ZwSearchForm row-num="3" :option="searchOption" @search="search" @reset="reset" />
        <ZwTable
            ref="tableRef"
            class="table-box"
            tab-h="initial"
            :option="tableOption"
            :fetch-params="state.searchParams"
            :fetch-api="fetchApi()">
            <template #headerOperateLeft>
                <div class="newTag">
                    <div class="time">最近一次同步时间为：{{ updateTime }}</div>
                </div>
            </template>
            <template #headerOperate>
                <div class="btn">
                    <el-button
                        v-auth="'ADD_CUSTOMER_LABEL_GROUP'"
                        type="primary"
                        style="margin-right: 17px"
                        @click="openCreateTag">
                        新建客户标签组
                    </el-button>
                    <el-dropdown>
                        <el-button>
                            更多操作<el-icon class="el-icon--right">
                                <arrow-down />
                            </el-icon>
                        </el-button>
                        <template #dropdown>
                            <el-dropdown-menu>
                                <el-dropdown-item v-auth="'SYNC_WECOM'" @click="synchronization">
                                    同步至企微
                                </el-dropdown-item>
                                <el-dropdown-item v-auth="'MERGE_WECOM_LABEL'" @click="merge">
                                    合并企微标签
                                </el-dropdown-item>
                            </el-dropdown-menu>
                        </template>
                    </el-dropdown>
                </div>
            </template>
        </ZwTable>
        <ZWCreateTag ref="createTag" @submit="getCusTagList" />
        <!--删除标签组-->
        <Dialog :app-dialog="delDialog">
            <div class="del-dialog">
                <el-icon color="#E6A23C" size="18px"><WarningFilled /></el-icon>
                <div class="del-list">
                    <div class="del-title">
                        你确定要删除【{{ formData.name }}】标签组下面的{{ formData.tags.length }}个标签吗？
                    </div>
                    <div class="del-text">删除后，拥有该标签的客户将自动移除该标签。</div>
                    <div class="del-tip">
                        有
                        <span class="red-tip">{{ formData.cust_num }}</span>
                        个客户已拥有该标签组下的标签，请谨慎操作！
                    </div>
                </div>
            </div>
        </Dialog>
        <abnormalDialog ref="abnormalDialogRef"></abnormalDialog>
    </div>
</template>
<script lang="tsx" setup>
import { reactive, ref, computed } from 'vue';
import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZwTable from '@/components/zw/table/Table';

import ZWCreateTag from '../../../components/ZWCreateTag.vue';
import Dialog from '@/components/Dialog.vue';
import abnormalDialog from '../../../components/abnormalDialog.vue';
import { getTagsList, syncWE, syncToQW, getCusTags2, delTagGroup, tagNum } from '@/api/customerCenter';
import { getSyncTime } from '@/api/customerCenter/groupManage';
import { ElMessage, ElButton, ElTooltip } from 'element-plus';
import { deepCopy } from '@/utils/helper';
import { ShowTaskMessage } from '@/hooks/TaskMessageHooks';
import { parabolaAnimation } from '@/utils/parabola';

const createTag = ref(null);
const abnormalDialogRef = ref(null);
const updateTime = ref('');
const tableRef = ref();
//删除相关数据
const formData = reactive({
    group_id: '', // 标签组id
    name: '', // 标签组名称
    cust_num: '', // 标签组下客户数量
    tags: [] // 标签组
});
// 取消删除客户标签
const cancelDel = () => {
    delDialog.visible = false;
};
// 确认删除客户标签
const submitDel = e => {
    delTagGroup({
        group_id: formData.group_id
    })
        .then(() => {
            delDialog.visible = false;
            tableRef.value.reload();
            ElMessage.success('删除成功');
            if (formData.cust_num) {
                parabolaAnimation(e);
                ShowTaskMessage('客户标签删除异步任务创建成功');
            }
        })
        .catch((e: any) => {
            if (e?.code == 51042) {
                delDialog.visible = false;
                abnormalDialogRef.value.openAbnormal();
            }
        });
};
// 删除客户标签弹框配置
const delDialog = reactive({
    visible: false,
    title: '删除提醒',
    width: '400px',
    cancel: cancelDel,
    submit: submitDel,
    cancelText: '取消',
    submitText: '确定'
});
const defaultParams = reactive({
    type_list: [],
    keyword: ''
});
const state = reactive({
    searchParams: deepCopy(defaultParams)
});
const searchOption = computed(() => {
    return [
        {
            label: '标签搜索',
            name: 'keyword',
            value: '',
            type: 'input',
            width: '280px',
            placeholder: '请输入标签组/标签名称'
        },
        {
            label: '标签组类别',
            name: 'type_list',
            value: '',
            multiple: true,
            type: 'select',
            placeholder: '请选择标签组类别',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    getTagsList().then((r: any) => {
                        resolve(r);
                    });
                });
            },
            formatOption: (v: { name: any; id: any }) => ({
                label: v.name,
                value: v.id
            })
        }
    ];
});
const tableOption = [
    {
        prop: 'group_name',
        label: '标签组',
        width: 150
    },
    {
        prop: 'tags',
        label: '客户标签',
        isTag: true
    },
    {
        prop: 'count',
        label: '标签数',
        width: 120
    },
    {
        prop: 'group_type_value',
        label: '标签组类别',
        width: 180
    },
    {
        prop: 'created_at',
        label: '创建时间',
        width: 180
    },
    {
        prop: 'operate',
        label: '操作',
        fixed: 'right',
        width: 200,
        isOperate: true,
        renderOperate({ row, column, index }) {
            if (row.create_type != 4) {
                return (
                    <div class="handle">
                        <ElButton size="small" onClick={() => edit(row)} vAuth={'EDIT'}>
                            编辑
                        </ElButton>
                        <ElTooltip
                            effect="dark"
                            placement="top"
                            popper-class="tool-tip"
                            disabled={row.sys_qy_tag_group != 1}
                            vSlots={{ content: getContent() }}>
                            <span>
                                <ElButton
                                    size="small"
                                    disabled={row.sys_qy_tag_group == 1}
                                    onClick={() => del(row)}
                                    vAuth={'DEL'}>
                                    删除
                                </ElButton>
                            </span>
                        </ElTooltip>
                    </div>
                );
            }
        }
    }
];
const fetchApi = () => {
    return getCusTags2;
};
const search = (data: any) => {
    if (data.keyword) {
        data.keyword = data.keyword.trim();
    }
    state.searchParams = { ...deepCopy(data), type_list: data.type_list?.join(',') };
};
const reset = (v?: any) => {
    state.searchParams = deepCopy(v);
};
// 获取最后一次同步时间
const getSyncTimeFun = () => {
    getSyncTime({ sync_type: 100 }).then((r: any) => {
        updateTime.value = r.weiwork_synctime;
    });
};
getSyncTimeFun();
const openCreateTag = () => {
    createTag.value.appDialog.visible = true;
    createTag.value.appDialog.title = '新建客户标签组';
};
// 同步至企微
const synchronization = () => {
    syncWE().then(() => {
        ElMessage.success('同步成功');
    });
};
// 合并至企微
const merge = async () => {
    await syncToQW();
    ElMessage.success('合并成功');
};
// 获取列表数据
const getCusTagList = () => {
    tableRef.value.reload();
};
// 编辑客户标签组
const edit = (data: any) => {
    createTag.value.echo(data);
    createTag.value.appDialog.visible = true;
    createTag.value.appDialog.title = '编辑客户标签组';
};
// 删除
const del = (val: any) => {
    tagNum({ group_id: val.group_id }).then((res: any) => {
        formData.cust_num = res.cust_num;
        formData.group_id = val.group_id;
        formData.name = val.group_name;
        formData.tags = val.tags;
        delDialog.visible = true;
    });
};
// 获取提示语
const getContent = () => {
    return (
        <div>
            该标签组是企微后台创建的，不支持
            <br />
            删除，请至企微后台操作。
        </div>
    );
};
</script>
<style scoped lang="scss">
.table_container {
    height: calc(100vh - 242px);
    display: flex;
    flex-direction: column;

    .zw-table {
        display: flex;
        flex-direction: column;
        flex: 1;
        overflow: hidden;

        :deep(.el-table) {
            flex: 1;

            .el-table__empty-block {
                position: absolute;
                top: 50%;
                left: 50%;
                transform: translate(-50%, -50%);
            }
        }
    }
}

.container {
    border: 1px solid #eaeaea;

    .tag_box {
        display: flex;
        display: -webkit-box; //谷歌
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 1; //显示几行
        overflow: hidden;

        .form-tags {
            margin: 0 10px 0 0;
        }
    }

    .tagList {
        display: flex;
        align-items: center;
        flex-wrap: wrap;

        .tag_item {
            padding: 4px;
            color: #ff6b00;
            margin: 0 10px 10px 0;
            border-radius: 2px;
            border: 1px solid #ffc69e;

            &:nth-child(n + 15) {
                display: none;
            }
        }
    }

    .btn {
        display: flex;
        align-items: center;

        .btn_item {
            padding: 0 26px;
            background: #fff;
            border-radius: 2px;
            border: 1px solid #eaeaea;
            cursor: pointer;
        }
    }

    :deep .el-table tr {
        height: 70px;
    }
}

.conceal {
    display: flex;
    flex-wrap: wrap;

    &_tag_item {
        padding: 4px;
        color: #ff6b00;
        margin: 0 10px 10px 0;
        border-radius: 2px;
        border: 1px solid #ffc69e;
    }
}

.del-dialog {
    padding: 8px 0;
    display: flex;

    .del-list {
        padding-left: 8px;

        .del-title {
            font-size: 14px;
            font-weight: 600;
            color: #33302d;
            margin-bottom: 12px;
        }

        .del-text {
            font-size: 12px;
            font-weight: 400;
            color: #999;
            margin-bottom: 12px;
        }

        .del-tip {
            font-size: 12px;
            font-weight: 400;
            color: #33302d;

            .red-tip {
                color: red;
            }
        }
    }
}
</style>
<style lang="scss">
.popper {
    .pop_dialog {
        display: flex;
        flex-wrap: wrap;

        .form-tags {
            margin: 0 10px 10px 0;
        }
    }
}

.newTag {
    display: flex;
    align-items: center;
    justify-content: space-between;

    .time {
        font-size: 14px;
        font-weight: 300;
        color: #33302d;
    }
}
</style>
